# -*- coding=utf-8 -*-
'''
Created on Aug 10, 2016

@author: corvo
'''

from datetime import datetime
from Basehandler import BaseHandler
from Utlis.ReturnCodeConfig import CodeTable
from Database.tables import Express
from Utlis.Helper import get_card


class DeleteRecordHandler(BaseHandler):
    """
    删除某条订单记录, 需要提供uuid, 手机号码, 及时间戳
    请牢记, 已经接单的不可以删除
    """
    
    def post(self):
        retjson = {'code':200, 'content':''}

        try:
            _user_phone = self.get_argument('user_phone')
            _time_stamp = self.get_argument('sub_time')
            _uuid       = self.get_argument('uuid')

            #print (_user_phone)
            #print (_time_stamp)
            #print (_uuid)

        except Exception as e:
            print (e)
            retjson['code'] = 300
            retjson['content'] = CodeTable[300]
            self.write_back(retjson)
            return
            
            
        try:
            _submit_time = long(_time_stamp)
            _query_time  = datetime.fromtimestamp(_submit_time)
        except Exception as e:
            print (e)
            retjson['code'] = 303
            retjson['content'] = CodeTable[303]
            self.write_back(retjson)
            return
        
        _card_num = get_card(_uuid)
        
        if not _card_num:
            #print ("Wrong UUID")
            retjson['code'] = 301
            retjson['content'] = CodeTable[301]
            self.write_back(retjson)
            return
            
        # 生成sql语句
        exist_info = self.db.query(Express)                    \
                        .filter(Express.cardnum == _card_num , \
                                Express.phone == _user_phone , \
                                Express.submittime == _query_time ) 
                
        try:
            info = exist_info.one()
            
            # 如果已被接单, 不作任何操作
            if info.receiving :
                retjson['code'] = 304
                retjson['content'] = CodeTable[304]
                self.write_back(retjson)
                return

            exist_info.delete()

        except Exception as e:
            print (e)                   # 未查询到该项目, 因此返回200
            retjson['code'] = 200
            retjson['content'] = CodeTable[200]
            self.write_back(retjson)
            return
        
        try:
            self.db.commit()
            retjson['content'] = CodeTable[200]
        except Exception as e:
            print (e)
            self.db.rollback()
            retjson['code'] = 500
            retjson['content'] = CodeTable[500] # 修改数据库失败

        self.write_back(retjson)
        return
            
            
        
        
        
